package com.example.spring.bean.load03scope;

import com.example.spring.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * 多例测试
 * <p> 每次拿到的实例都是新 new 出来的
 * <p>
 */
public class PrototypeTest {

    @Bean
    @Scope("prototype")
    User proUser() {
        User user = new User();
        user.setName("proUser");
        user.setId(22);
        return user;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrototypeTest.class);

        Object prototype1 = context.getBean("proUser");
        Object prototype2 = context.getBean("proUser");

        //不是同一个实例，每次获取的时候都要初始化一次
        System.out.println(prototype1 == prototype2); //false

        User bean = context.getBean(User.class);
        System.out.println(prototype1 == bean); //false
        System.out.println(prototype2 == bean); //false

        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            //仅打印一个proUser
            System.out.println(name);
        }

        context.close();
    }
}
